package treepro;

import java.awt.Dimension;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author Ivan
 */
public class UtilXML {

    public static void xmlTographicsObjects(File file_xml) {
        List<GraphicObject> ret = TreeProApp.main.treePanel.objects;//new ArrayList<GraphicObject>();
        try {
            File file = file_xml;
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(file);

            Element root = doc.getDocumentElement();

            TreeProApp.main.treePanel.setScreenSize(new Dimension(Integer.parseInt(root.getAttribute("screenw")), Integer.parseInt(root.getAttribute("screenh"))));
            NodeList nodes = doc.getElementsByTagName("node");
            if (nodes.getLength() != 0) {
                try {
                    for (int i = 0; i < nodes.getLength(); i++) {
                        Node node = nodes.item(i);
                        Element e = (Element) node;
                        ret.add(new NodeObject(
                                e.getTextContent(), 
                                Boolean.parseBoolean(e.getAttribute("fu_enable")), 
                                Integer.parseInt(e.getAttribute("fu_value")), 
                                Double.parseDouble(e.getAttribute("lapTime")), 
                                Double.parseDouble(e.getAttribute("unloadTime")), 
                                Double.parseDouble(e.getAttribute("volume")), 
                                Double.parseDouble(e.getAttribute("left")), 
                                Double.parseDouble(e.getAttribute("top")), 
                                Integer.parseInt(e.getAttribute("radius")),
                                Integer.parseInt(e.getAttribute("number")),
                                Boolean.parseBoolean(e.getAttribute("skvoz"))
                                ));
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            
            NodeList lines = doc.getElementsByTagName("line");
            if (lines.getLength() != 0) {
                try {
                    for (int i = 0; i < lines.getLength(); i++) {
                        Node node = lines.item(i);
                        Element e = (Element) node;
                        ret.add(new LineObject(
                                Float.parseFloat(e.getAttribute("distance")), 
                                Boolean.parseBoolean(e.getAttribute("nesimetr")), 
                                Boolean.parseBoolean(e.getAttribute("orient")), 
                                Boolean.parseBoolean(e.getAttribute("osob")), 
                                Double.parseDouble(e.getAttribute("speed")),
                                Integer.parseInt(e.getAttribute("no1")), 
                                Integer.parseInt(e.getAttribute("no2")),
                                e.getTextContent()
                                ));
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            
            
            System.out.println("LoadFromXML: " + file.getName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return;
    }

    /**
     * Сохранить списки в xml файл
     * @param collectModels 
     */
    public static boolean graphicsObjectsToXML(List<GraphicObject> graphicObjects, File file) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            DOMImplementation impl = builder.getDOMImplementation();
            Element e = null;
            Node n = null;

            Document xmldoc = null;
            xmldoc = impl.createDocument(null, "settings", null);
            Element root = xmldoc.getDocumentElement();
            root.setAttribute("screenw", TreeProApp.main.treePanel.getScreenWidth() + "");
            root.setAttribute("screenh", TreeProApp.main.treePanel.getScreenHeight() + "");

            for (Iterator<GraphicObject> it = graphicObjects.iterator(); it.hasNext();) {
                GraphicObject graphicObject = it.next();


                if (graphicObject instanceof NodeObject) {
                    e = xmldoc.createElementNS(null, "node");
                    //e.setAttributeNS(null, "type", "node");
                    e.setAttributeNS(null, "number", ((NodeObject) graphicObject).getNumber() + "");
                    e.setAttributeNS(null, "fu_enable", ((NodeObject) graphicObject).fu_enable + "");
                    e.setAttributeNS(null, "fu_value", ((NodeObject) graphicObject).fu_value + "");
                    e.setAttributeNS(null, "lapTime", ((NodeObject) graphicObject).lapTime + "");
                    e.setAttributeNS(null, "unloadTime", ((NodeObject) graphicObject).unloadTime + "");
                    e.setAttributeNS(null, "volume", ((NodeObject) graphicObject).volume + "");
                    e.setAttributeNS(null, "left", ((NodeObject) graphicObject).getLeft() + "");
                    e.setAttributeNS(null, "top", ((NodeObject) graphicObject).getTop() + "");
                    e.setAttributeNS(null, "radius", ((NodeObject) graphicObject).getRadius() + "");
                    e.setAttributeNS(null, "skvoz", ((NodeObject) graphicObject).skvoz + "");
                }
                if (graphicObject instanceof LineObject) {
                    e = xmldoc.createElementNS(null, "line");
                    //e.setAttributeNS(null, "type", "line");
                    e.setAttributeNS(null, "distance", ((LineObject) graphicObject).distance + "");
                    e.setAttributeNS(null, "nesimetr", ((LineObject) graphicObject).nesimetr + "");
                    e.setAttributeNS(null, "orient", ((LineObject) graphicObject).orient + "");
                    e.setAttributeNS(null, "osob", ((LineObject) graphicObject).osob + "");
                    e.setAttributeNS(null, "speed", ((LineObject) graphicObject).speed + "");
                    e.setAttributeNS(null, "no1", ((LineObject) graphicObject).getNo1().getNumber() + "");
                    e.setAttributeNS(null, "no2", ((LineObject) graphicObject).getNo2().getNumber() + "");
                }
                n = xmldoc.createTextNode(graphicObject.getName());
                e.appendChild(n);
                root.appendChild(e);
            }
            DOMSource source = new DOMSource(xmldoc);

            StreamResult streamResult = new StreamResult(file);
            //StreamResult streamResult = new StreamResult(new File(outDir+ frameName + collectModel.getName() + ".xml"));
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer serializer = tf.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            //serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"users.dtd");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.transform(source, streamResult);
            System.out.println("GenerateXML: " + file.getName());
            return true;

        } catch (Exception ex) {
            ex.printStackTrace();

        }
        return false;
    }
}
